package com.example.securitydemo.config;

import com.example.securitydemo.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.util.Collection;

/**
 * 登录成功时返回json信息的配置
 */
public class DemoAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // 生成jwt token
        String accessToken = JwtUtils.genAccessToken(authentication.getName());
        response.setHeader(JwtUtils.REQ_HEADER_AUTH, accessToken);
        Object principal = authentication.getPrincipal(); // 获取用户身份信息
        Object credentials = authentication.getCredentials(); // 获取用户凭证信息
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); // 获取用户权限信息
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(DemoResult.success(principal));
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(json);
    }
}
